import * as vscode from 'vscode';
import { exec } from 'child_process';
import { promisify } from 'util';

const execAsync = promisify(exec);

export function activate(context: vscode.ExtensionContext) {
    console.log('Git Log Reader extension is now active!');

    // 创建侧边栏视图提供者
    const provider = new GitLogSidebarProvider(context.extensionUri);
    
    // 注册侧边栏视图 - 使用正确的选项
    context.subscriptions.push(
        vscode.window.registerWebviewViewProvider('gitLogReader.sidebar', provider, {
            webviewOptions: {
                retainContextWhenHidden: true
            }
        })
    );

    // 注册刷新命令
    let refreshCommand = vscode.commands.registerCommand('gitLogReader.refresh', () => {
        provider.refresh();
    });

    // 保留原有的命令（可选）
    let showCommand = vscode.commands.registerCommand('gitLogReader.showGitLog', async () => {
        const panel = vscode.window.createWebviewPanel(
            'gitLogReader',
            'Git Log Reader',
            vscode.ViewColumn.One,
            {
                enableScripts: true,
                retainContextWhenHidden: true
            }
        );

        panel.webview.html = getWebviewContent();

        // 处理来自webview的消息
        panel.webview.onDidReceiveMessage(
            async message => {
                switch (message.command) {
                    case 'showGitLog':
                        const gitLog = await getGitLog(message.style);
                        panel.webview.postMessage({
                            command: 'displayGitLog',
                            content: gitLog,
                            style: message.style
                        });
                        break;
                }
            },
            undefined,
            context.subscriptions
        );
    });

    context.subscriptions.push(refreshCommand, showCommand);
}

class GitLogSidebarProvider implements vscode.WebviewViewProvider {
    public static readonly viewType = 'gitLogReader.sidebar';

    private _view?: vscode.WebviewView;

    constructor(
        private readonly _extensionUri: vscode.Uri,
    ) { }

    public resolveWebviewView(
        webviewView: vscode.WebviewView,
        context: vscode.WebviewViewResolveContext,
        _token: vscode.CancellationToken,
    ) {
        this._view = webviewView;

        webviewView.webview.options = {
            enableScripts: true,
            localResourceRoots: [
                this._extensionUri
            ]
        };

        webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);

        // 处理来自webview的消息
        webviewView.webview.onDidReceiveMessage(
            async message => {
                switch (message.command) {
                    case 'showGitLog':
                        const gitLog = await getGitLog(message.style);
                        webviewView.webview.postMessage({
                            command: 'displayGitLog',
                            content: gitLog,
                            style: message.style
                        });
                        break;
                }
            }
        );
    }

    public refresh() {
        if (this._view) {
            this._view.webview.postMessage({
                command: 'refresh'
            });
        }
    }

    private _getHtmlForWebview(webview: vscode.Webview) {
        return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Git Log Reader</title>
    <style>
        body {
            font-family: var(--vscode-font-family);
            font-size: var(--vscode-font-size);
            color: var(--vscode-foreground);
            background-color: var(--vscode-sideBar-background);
            padding: 10px;
            margin: 0;
        }
        
        .header {
            text-align: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--vscode-sideBar-border);
        }
        
        .header h2 {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
        }
        
        .button-container {
            display: flex;
            flex-direction: column;
            gap: 8px;
            margin-bottom: 15px;
        }
        
        .btn {
            padding: 8px 12px;
            font-size: 13px;
            border: 1px solid var(--vscode-button-border);
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
            text-align: center;
            font-weight: 500;
        }
        
        .btn-awesome {
            background-color: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
        }
        
        .btn-awesome:hover {
            background-color: var(--vscode-button-hoverBackground);
        }
        
        .btn-simple {
            background-color: var(--vscode-button-secondaryBackground);
            color: var(--vscode-button-secondaryForeground);
        }
        
        .btn-simple:hover {
            background-color: var(--vscode-button-secondaryHoverBackground);
        }
        
        #gitLogContent {
            background-color: var(--vscode-editor-background);
            border: 1px solid var(--vscode-panel-border);
            border-radius: 4px;
            padding: 10px;
            font-family: var(--vscode-editor-font-family);
            font-size: var(--vscode-editor-font-size);
            white-space: pre-wrap;
            max-height: 400px;
            overflow-y: auto;
            color: var(--vscode-editor-foreground);
        }
        
        .loading {
            text-align: center;
            font-style: italic;
            opacity: 0.7;
            color: var(--vscode-descriptionForeground);
        }
        
        .awesome-style {
            color: var(--vscode-gitDecoration-addedResourceForeground);
        }
        
        .simple-style {
            color: var(--vscode-editor-foreground);
        }

        .empty-state {
            text-align: center;
            padding: 20px;
            color: var(--vscode-descriptionForeground);
            font-style: italic;
        }
    </style>
</head>
<body>
    <div class="header">
        <h2>🚀 Git Log Reader</h2>
    </div>
    
    <div class="button-container">
        <button class="btn btn-awesome" onclick="showGitLog('awesome')">
            🔥 牛逼一点
        </button>
        <button class="btn btn-simple" onclick="showGitLog('simple')">
            📝 朴素一点
        </button>
    </div>
    
    <div id="gitLogContent" class="empty-state">
        点击上方按钮查看 Git 日志...
    </div>

    <script>
        const vscode = acquireVsCodeApi();
        
        function showGitLog(style) {
            document.getElementById('gitLogContent').innerHTML = '正在加载 Git 日志...';
            document.getElementById('gitLogContent').className = 'loading';
            
            vscode.postMessage({
                command: 'showGitLog',
                style: style
            });
        }
        
        window.addEventListener('message', event => {
            const message = event.data;
            switch (message.command) {
                case 'displayGitLog':
                    const content = document.getElementById('gitLogContent');
                    content.innerHTML = message.content;
                    content.className = message.style === 'awesome' ? 'awesome-style' : 'simple-style';
                    break;
                case 'refresh':
                    document.getElementById('gitLogContent').innerHTML = '点击上方按钮查看 Git 日志...';
                    document.getElementById('gitLogContent').className = 'empty-state';
                    break;
            }
        });
    </script>
</body>
</html>`;
    }
}

async function getGitLog(style: string): Promise<string> {
    try {
        const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
        if (!workspaceFolder) {
            return 'No workspace folder found';
        }

        const workspacePath = workspaceFolder.uri.fsPath;
        
        // 根据样式选择不同的git log格式
        let gitCommand = '';
        if (style === 'awesome') {
            gitCommand = 'git log --oneline --graph --decorate --color=always -10';
        } else {
            gitCommand = 'git log --oneline -10';
        }
        
        const { stdout, stderr } = await execAsync(gitCommand, {
            cwd: workspacePath
        });

        if (stderr) {
            return `Git error: ${stderr}`;
        }

        return stdout;
        
    } catch (error) {
        return `Error reading git log: ${error}`;
    }
}

function getWebviewContent(): string {
    return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Git Log Reader</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            margin: 0;
            color: white;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
        }
        
        h1 {
            text-align: center;
            margin-bottom: 30px;
            font-size: 2.5em;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
        }
        
        .button-container {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .btn {
            padding: 15px 30px;
            font-size: 18px;
            border: none;
            border-radius: 50px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .btn-awesome {
            background: linear-gradient(45deg, #ff6b6b, #ee5a24);
            color: white;
            box-shadow: 0 4px 15px rgba(255, 107, 107, 0.4);
        }
        
        .btn-awesome:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(255, 107, 107, 0.6);
        }
        
        .btn-simple {
            background: linear-gradient(45deg, #74b9ff, #0984e3);
            color: white;
            box-shadow: 0 4px 15px rgba(116, 185, 255, 0.4);
        }
        
        .btn-simple:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(116, 185, 255, 0.6);
        }
        
        #gitLogContent {
            background: rgba(0, 0, 0, 0.3);
            border-radius: 10px;
            padding: 20px;
            font-family: 'Courier New', monospace;
            white-space: pre-wrap;
            max-height: 500px;
            overflow-y: auto;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .loading {
            text-align: center;
            font-style: italic;
            opacity: 0.7;
        }
        
        .awesome-style {
            color: #00ff88;
            text-shadow: 0 0 10px rgba(0, 255, 136, 0.5);
        }
        
        .simple-style {
            color: #ffffff;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 Git Log Reader</h1>
        <div class="button-container">
            <button class="btn btn-awesome" onclick="showGitLog('awesome')">
                🔥 牛逼一点
            </button>
            <button class="btn btn-simple" onclick="showGitLog('simple')">
                📝 朴素一点
            </button>
        </div>
        <div id="gitLogContent" class="loading">
            点击上方按钮查看 Git 日志...
        </div>
    </div>

    <script>
        const vscode = acquireVsCodeApi();
        
        function showGitLog(style) {
            document.getElementById('gitLogContent').innerHTML = '正在加载 Git 日志...';
            document.getElementById('gitLogContent').className = 'loading';
            
            vscode.postMessage({
                command: 'showGitLog',
                style: style
            });
        }
        
        window.addEventListener('message', event => {
            const message = event.data;
            switch (message.command) {
                case 'displayGitLog':
                    const content = document.getElementById('gitLogContent');
                    content.innerHTML = message.content;
                    content.className = message.style === 'awesome' ? 'awesome-style' : 'simple-style';
                    break;
            }
        });
    </script>
</body>
</html>`;
}

export function deactivate() {}